/**
 * Copyright (c) 2021-2028, iron.guo 郭成杰 (jiedreams@sina.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdl.configuration;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.beluga.core.BPay;
import com.beluga.core.model.wechat.WxBPayOrderQuery;
import com.beluga.core.util.Func;
import com.xdl.modules.constant.OrderEnum;
import com.xdl.modules.entity.WxActivityDetail;
import com.xdl.modules.entity.WxOrderDetail;
import com.xdl.modules.entity.WxOwnerCoupon;
import com.xdl.modules.service.WxActivityDetailService;
import com.xdl.modules.service.WxOrderDetailService;
import com.xdl.modules.service.WxOwnerCouponService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * @Author iron.guo
 * @Date 2022/5/6
 * @Description
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private WxOrderDetailService detailService;

    @Autowired
    private BPay bPay;

    @Autowired
    private WxOwnerCouponService ownerCouponService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对 redis 数据失效事件，进行数据处理
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.info("onPMessageinfo开始监听:{}", "pattern = [" + pattern + "],  message = [" + message + "]");
        String listener = message.toString();
        //step 1 过滤key是否为订单
        if (listener.contains("XDLORDER_")) {
            String key = listener.split("_")[1];
            //step 2 查询订单是否已支付
            QueryWrapper<WxOrderDetail> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(WxOrderDetail::getOrderSn, key);
            WxOrderDetail orderDetail = detailService.getOne(wrapper);
            if (Func.isNotEmpty(orderDetail)) {
                WxBPayOrderQuery orderQuery = bPay.queryWxOrder(orderDetail.getTransactionId(), orderDetail.getOrderSn());
                String tradeState = orderQuery.getTradeState();
                //step 3 更新订单为取消支付
                if (tradeState.equals("NOTPAY")) {
                    orderDetail.setStatus(OrderEnum.LOST_EFFICACY).setPayStatus(OrderEnum.OVERDUE_PAY);
                    detailService.updateById(orderDetail);
                    //调用关闭订单
                    //退还优惠券
                    this.backCoupon(orderDetail.getCouponId());
                    log.warn("订单编号: {} 已超时支付，订单取消",key);
                } else if (tradeState.equals("SUCCESS")) {
                    orderDetail.setStatus(OrderEnum.IS_BPAY).setPayStatus(OrderEnum.IS_PAY);
                    detailService.updateById(orderDetail);
                    log.warn("订单编号: {} 已支付",key);
                }

            }

        }


    }


    private void backCoupon(Long couponId) {
        //退还优惠券
        if (Func.isNotEmpty(couponId) && couponId != -1) {
            WxOwnerCoupon wxOwnerCoupon = ownerCouponService.getById(couponId);
            wxOwnerCoupon.setStatus(1);
            ownerCouponService.updateById(wxOwnerCoupon);
        }

    }


}
